/**
 * Copyright 2009 by Christian Scheid. This file is part of the switch eclipse plugin and is licensed under the GPL
 * version 3. Please refer to the URL http://www.gnu.org/licenses/gpl-3.0.html for details.
 */
package org.digitalsoul.switchplugin.prefs;

import org.digitalsoul.switchplugin.SwitchPlugin;
import org.digitalsoul.switchplugin.model.Configuration;
import org.digitalsoul.switchplugin.prefs.util.XMLConverter;
import org.eclipse.jface.preference.IPreferenceStore;

import com.thoughtworks.xstream.converters.ConversionException;

public class Preferences {

    private static final String SWITCH_ITEMS_KEY = "org.digitalsoul.switchplugin";
    private static Configuration currentConfig;

    public static void save(Configuration config) {
        currentConfig = config;
        getStore().setValue(SWITCH_ITEMS_KEY, XMLConverter.configToXML(config));
    }

    public static Configuration load() {
        if (currentConfig == null) {
            String prefsXML = getStore().getString(SWITCH_ITEMS_KEY);
            currentConfig = getDefaults();
            if (prefsXML != null && prefsXML.length() > 0) {
                currentConfig = decode(prefsXML);
            }
        }
        return currentConfig;
    }

    public static IPreferenceStore getStore() {
        return SwitchPlugin.getDefault().getPreferenceStore();
    }

    public static Configuration decode(String xml) {
        Configuration config = null;
        try {
            config = XMLConverter.xmlToConfig(xml);
        }
        catch (ConversionException e) {
            config = getDefaults();
        }
        return config;
    }

    public static void setupDefaults() {
        getStore().setDefault(SWITCH_ITEMS_KEY, XMLConverter.configToXML(getDefaults()));
    }

    public static Configuration getDefaults() {
        return new Configuration();
    }
}